import type { RouteMeta, RouteRecordRaw } from 'vue-router'

/**
 * @desc 合并 route meta
 * @param routes 路由
 * @param defaultMeta 默认 meta
 * @param extendParent 是否继承父级(仅includeKeys) meta (default: true)
 */
export function mergeMeta(
  routes: RouteRecordRaw[],
  defaultMeta: RouteMeta,
  extendParent = true
): RouteRecordRaw[] {
  return routes.map<RouteRecordRaw>((route) => {
    const mergedMeta = { ...defaultMeta, ...(route.meta ?? {}) }

    if (route.children) {
      const childrenDefaultMeta = extendParent
        ? (Object.fromEntries(
            Reflect.ownKeys(defaultMeta).map((key) => [key, mergedMeta[key]])
          ) as RouteMeta)
        : defaultMeta

      return {
        ...route,
        meta: mergedMeta,
        children: mergeMeta(route.children, childrenDefaultMeta, extendParent)
      }
    }

    return { ...route, meta: mergedMeta }
  })
}
